<template>
  <div>
    <el-card
      :body-style="{padding: '0px'}"
      :page-count='cur_pageSize'
      :total='total'
      :current-page='cur_page'
      @current-change='pageCurrentChangeHandle'
    >
        <el-form class='p-4' inline @submit.prevent.native>
          <el-form-item>
            <el-input
              v-model='snOrTid'
              maxlength='30'
              :placeholder="$t('batch.dev_sn')"
              clearable
              @blur='() => snOrTid = snOrTid.trim()'
              @keyup.enter='search'
            />
          </el-form-item>
          <el-form-item v-show="showFormItem('OPERATOR_NAME')">
            <el-input
              v-model='operatorName'
              maxlength='30'
              :placeholder="$t('device.operatorName')"
              clearable
              @blur='() => operatorName = operatorName.trim()'
              @keyup.enter.native='fetchData'
            />
          </el-form-item>
          <el-form-item v-show="showFormItem('STATUS')">
            <el-select
              v-model='status'
              clearable
              :placeholder="$t('device.status')"
              @keyup.enter.native='fetchData'
            >
              <el-option
                v-for='item in statusObj'
                :key="item.val + '_status'"
                :label='item.name'
                :value='item.val'
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="showFormItem('ACTIVATION_TIME')">
            <el-date-picker
              v-model='activeDate'
              type='daterange'
              value-format='timestamp'
              :start-placeholder="$t('common.start_time')"
              :end-placeholder="$t('common.end_time')"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type='primary'
              class='w-8'
              @click='search'
            >
              <svg-icon icon-class='Search' />
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-dropdown
              trigger='click'
              @command='handleCommandImport'
            >
              <el-button
                v-permission="{
                  permission:'10400008.MANAGE',
                  condition:{}
                }"
                size='medium'
                class='w-8'
                type='primary'
              >
                <svg-icon icon-class='Plus' />
              </el-button>
              <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command='inputBoxSn'>{{ $t('batch.by_singleInputBoxSn') }}
                </el-dropdown-item>
                <!--                <el-dropdown-item command='inputBoxTid'>{{ $t('batch.by_singleInputBoxTid') }}-->
                <!--                </el-dropdown-item>-->
                <el-dropdown-item command='app'>{{ $t('batch.by_app') }}
                </el-dropdown-item>
                <el-dropdown-item command='firmware'>{{ $t('batch.by_firmware') }}
                </el-dropdown-item>
                <el-dropdown-item command='file'>{{ $t('batch.by_fileImport') }}</el-dropdown-item>
              </el-dropdown-menu></template>
            </el-dropdown>
          </el-form-item>

          <el-form-item>
            <el-dropdown trigger='click' @command='handleCommandDelete'>
              <el-button
                v-permission="{
                  permission:'10400008.MANAGE',
                  condition:{}
                }"
                size='medium'
                class='w-8'
                type='danger'
              >
                <svg-icon icon-class='Delete' />
              </el-button>
              <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command='inputBoxSn'>{{ $t('batch.by_singleInputBoxSn') }}
                </el-dropdown-item>
                <!--                <el-dropdown-item command='inputBoxTid'>{{ $t('batch.by_singleInputBoxTid') }}-->
                <!--                </el-dropdown-item>-->
                <el-dropdown-item command='file'>{{ $t('batch.by_fileImport') }}</el-dropdown-item>
              </el-dropdown-menu></template>
            </el-dropdown>
          </el-form-item>

          <el-form-item>
            <el-button size='medium' type='primary' class='w-8' @click='handleCommandExport'>
              <svg-icon icon-class='Download' />
            </el-button>
          </el-form-item>
          <el-form-item style='float: right;'>
            <el-button
              size='medium'
              class='w-8 '
              type='primary'
            >
              <table-column-filter
                :list='settingList'
                :default-setting='defaultSettings'
                v-model:settings='settings'
                domain='tms.batch.list'
              />
            </el-button>

          </el-form-item>
        </el-form>
      <div
        v-permission="{permission: ['10400008.MANAGE']}"
        class='selected-batch-button flex'
        :class="selectedData.length > 0 ? 'active' : ''"
      >
        <span class='label' style='line-height: 25px;'>
          {{ selectedData.length }} {{ $t('common.deals') }}
        </span>
          <el-button
            class="w-8 ml-4"
            type="primary"
            :disabled='selectedData.length < 1'
            :class="selectedData.length >= 1 ? 'active' : ''"
            @click='handleDeleteSn'
          >
            <svg-icon icon-class='delete' />
            <!-- {{ $t('common.delete') }} -->
          </el-button>
      </div>
      <el-table
        v-loading='listLoading'
        :data='tableData'
        class='terminal-table'
        :show-overflow-tooltip='true'
        @selection-change='handleSelectionChange'
        stripe
      >
        <el-table-column type='selection' width="60"/>
        <el-table-column label='SN' prop='devSn'>
          <template v-slot="scope">
            {{ scope.row.devSn }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader($t('MODEL'))"
          :label="$t('device.modelCode')"
          prop='modelName'
        />
<!--        <el-table-column-->
<!--          v-if="showHeader('TID')"-->
<!--          :label="$t('device.tid')"-->
<!--          prop='devTid'-->
<!--        />-->

        <el-table-column
          v-if="showHeader('REMARK')"
          :label="$t('device.remark')"
          prop='remark'
        />
        <el-table-column
          v-if="showHeader('OPERATOR')"
          :label="$t('device.operatorName')"
          prop='operatorName'
        />
        <el-table-column
          v-if="showHeader('STATUS')"
          :label="$t('device.status')"
          prop='status'
        >
          <template v-slot="{row}">
            <span>{{ statusFilter(row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('IS_ONLINE')"
          :label="$t('device.online')"
          prop='isOnline'
          width='120px'
        >
          <template v-slot="{row}">
            <el-tag
              :type="row.isOnline ? 'success' : 'info'"
              size='small'
            >
              <span>{{ row.isOnline ? $t('common.online') : $t('common.offline') }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('ACTIVATION_TIME')"
          :label="$t('device.activeTime')"
          prop='activeTime'
        >
          <template v-slot="{row}">
            <div :title='timeFilter(row.activeTime)'>
              {{ dateFilter( row.activeTime ) }}
            </div>
          </template>
        </el-table-column>

      </el-table>

    </el-card>
    <!-- inputBox SN导入提示框 -->
    <sn-import-dialog
      v-model='inputBox_importVisibleSn'
      :batch-id='batchId'
      @refreshDataList='freshTerminalCount'
    />
    <!-- inputBox TID导入提示框 -->
    <tid-import-dialog
      v-model='inputBox_importVisibleTid'
      :batch-id='batchId'
      @refreshDataList='freshTerminalCount'/>
    <!-- file导入提示框 -->
    <file-import-dialog v-model='file_importVisible' :batch-id='batchId' @fileImportErrInfo='fileImportErrInfo'
                        @refreshDataList='freshTerminalCount'>
    </file-import-dialog>

    <!-- sn输入框 删除提示框 -->
    <sn-delete-dialog v-model='inputBox_deleteVisibleSn' :batch-id='batchId'
                      @refreshDataList='freshTerminalCount'></sn-delete-dialog>
    <!-- sn输入框 删除提示框 -->
    <tid-delete-dialog v-model='inputBox_deleteVisibleTid' :batch-id='batchId'
                       @refreshDataList='freshTerminalCount'></tid-delete-dialog>
    <!-- file 删除提示框 -->
    <file-delete-dialog v-model='file_deleteVisible' :batch-id='batchId'
                        @refreshDataList='freshTerminalCount'
                        @fileDeleteErrInfo='fileDeleteErrInfo'></file-delete-dialog>
    <batch-result
      ref='batchResult'
      v-model='resultDetailsVisible'
      @close='resultDetailsVisible = false'
      @refreshDataList='freshTerminalCount'
    />
    <import-terminal-by-app
      v-model='app_importVisible'
      :batch-id='batchId'
      @close='app_importVisible = false'
      @refreshDataList='freshTerminalCount'
    />
    <import-terminal-by-firmware
      v-model='firmware_importVisible'
      :batch-id='batchId'
      @refreshDataList='freshTerminalCount'
    />
  </div>
</template>

<script>
import {
  queryBatchDevicePage,
  delBatchLegalDevices
} from '@/api/batch'
import { mapGetters } from 'vuex'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
import axios from 'axios'
import store from '@/store'
import { timeFilter, dateFilter } from '@/filters'
import TableColumnFilter from '../../../../components/page-setting/table-column-filter'
import BatchResult from '../components/batch-result'
import ImportTerminalByFirmware from '@/views/tms/group/components/ImportTerminalByFirmware'
import FileDeleteDialog from '@/views/tms/group/components/terminal/FileDeleteDialog'
import FileImportDialog from '@/views/tms/group/components/terminal/FileImportDialog'
import ImportTerminalByApp from '@/views/tms/group/components/ImportTerminalByApp'
import SnImportDialog from '@/views/tms/group/components/terminal/SnImportDialog'
import SnDeleteDialog from '@/views/tms/group/components/terminal/SnDeleteDialog'
import TidImportDialog from '@/views/tms/group/components/terminal/TidImportDialog'
import TidDeleteDialog from '@/views/tms/group/components/terminal/TidDeleteDialog'

export default {
  components: {
    FileDeleteDialog,
    FileImportDialog,
    ImportTerminalByFirmware,
    ImportTerminalByApp,
    TableColumnFilter,
    BatchResult,
    SnImportDialog,
    SnDeleteDialog,
    TidImportDialog,
    TidDeleteDialog
  },
  props: {
    childData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      settings: {
        conditions: [],
        columns: []
      },
      loading: false,
      selectedData: [],
      batchId: this.childData.batchId,
      listLoading: false,
      key_word: '',
      tableData: [],
      total: 0,
      cur_page: 1,
      cur_pageSize: 10,
      snOrTid: '',
      // orgId: '',
      // mrchNameOrMid: '',
      operatorName: '',
      status: '',
      activeDate: [],
      isVaild: true,
      inputBox_importVisibleSn: false,
      inputBox_importVisibleTid: false,
      file_importVisible: false,
      app_importVisible: false,
      firmware_importVisible: false,
      importForm: {
        batchId: this.childData.batchId,
        devSn: ''
      },
      inputBox_deleteVisibleSn: false,
      inputBox_deleteVisibleTid: false,
      file_deleteVisible: false,
      command: undefined,
      deleteFileModel: { 'fileList': [] },
      fileList: [],
      headers: { 'WEB-TOKEN': getToken() },
      resultDetailsVisible: false,
      actionType: undefined
    }
  },
  computed: {
    ...mapGetters(['orgs']),
    settingList() {
      return {
        conditions: [
          {
            title: this.$t('device.operatorName'),
            code: 'OPERATOR_NAME'
          },
          {
            title: this.$t('device.status'),
            code: 'STATUS'
          },

          {
            title: this.$t('device.activeTime'),
            code: 'ACTIVATION_TIME'
          }
        ],
        columns: [
          {
            title: this.$t('device.modelCode'),
            code: 'MODEL'
          },
          // {
          //   title: this.$t('device.tid'),
          //   code: 'TID'
          // },
          {
            title: this.$t('device.remark'),
            code: 'REMARK'
          },
          {
            title: this.$t('device.operatorName'),
            code: 'OPERATOR'
          },
          // this.$t('common.online'),
          {
            title: this.$t('device.status'),
            code: 'STATUS'
          },
          {
            title: this.$t('device.online'),
            code: 'IS_ONLINE'
          },
          {
            title: this.$t('device.activeTime'),
            code: 'ACTIVATION_TIME'
          }
        ]
      }
    },
    defaultSettings() {
      return {

        conditions: [
          'STATUS'
        ],
        columns: [
          'MODEL',
          'STATUS',
          'IS_ONLINE',
          'ACTIVATION_TIME'
        ]
      }
    },
    statusObj() {
      return [
        {
          val: 1,
          name: this.$t('device.activateStatus')
        },
        {
          val: 9,
          name: this.$t('device.inProductionStatus')
        }
      ]
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
  },
  methods: {
    dateFilter,
    timeFilter,
    statusFilter(status) {
      const statusMap = {
        1: this.$t('device.activateStatus'),
        9: this.$t('device.inProductionStatus')
      }
      return statusMap[status]
    },
    onlineFilter(status) {
      const statusMap = {
        false: this.$t('common.offline'),
        true: this.$t('common.online')
      }
      return statusMap[status]
    },
    showHeader(label) {
      var list = this.settings['columns']
      return list ? list.includes(label) : false
    },
    showFormItem(label) {
      var list = this.settings['conditions']
      return list ? list.includes(label) : false
    },
    pageCurrentChangeHandle(val) {
      this.cur_page = val
      this.fetchData()
    },
    fileImportErrInfo(res) {
      console.log(res)
      if (!res.importByAsnc) {
        this.$message.success(this.$t('common.import_processing'))
        this.search()
        this.$emit('freshTerminalCount', null)
        this.$store.dispatch('app/fetchTaskData')
      } else {
        if (res.errorCounts > 0) {
          this.$refs['batchResult'].init(res, 'add', this.batchId)
          this.resultDetailsVisible = true
        } else {
          this.$message.success(this.$t('batch.tip_file_add_success', res))
          this.search()
          this.$emit('freshTerminalCount', null)
        }
      }
    },
    fileDeleteErrInfo(res) {
      console.log(res)
      if (res.errorCounts > 0) {
        this.$refs['batchResult'].init(res, 'delete', this.batchId)
        this.resultDetailsVisible = true
      } else {
        this.$message.success(this.$t('batch.tip_file_delete_success', res))
        this.search()
        this.$emit('freshTerminalCount', null)
      }
    },
    fetchData() {
      let startTime, endTime
      if (this.activeDate) {
        this.activeDate.forEach((val, index) => {
          if (index === 0) {
            startTime = val / 1000
          } else if (index === 1) {
            endTime = val / 1000 + 24 * 60 * 60
          }
        })
      }
      this.listLoading = true
      queryBatchDevicePage({
        batchId: this.batchId,
        isValid: this.isVaild,
        devSn: this.snOrTid,
        status: this.status,
        operatorName: this.operatorName,
        mrchNameOrMid: this.mrchNameOrMid,
        activeStartTime: startTime,
        activeEndTime: endTime,
        pageNo: this.cur_page,
        pageSize: this.cur_pageSize
      }).then((res) => {
        this.tableData = res.data
        this.total = res.rows
      }).finally(() => {
        this.listLoading = false
      })
      // setTimeout(() => {
      //   this.listLoading = false
      //   bus.$emit('freshTerminalCount')
      // }, 200)
    },
    handleSelectionChange(val) {
      this.selectedData = val
    },
    parseTime,
    freshTerminalCount() {
      this.search()
      this.$bus.emit('freshTerminalCount')
    },
    search() {
      this.cur_page = 1
      this.fetchData()

    },
    handleCommandImport(command) {
      this.loading = false
      this.command = command
      if (command === 'inputBoxSn') {
        this.inputBox_importVisibleSn = true
      } else if (command === 'inputBoxTid') {
        this.inputBox_importVisibleTid = true
      } else if (command === 'file') {
        this.file_importVisible = true
      } else if (command === 'app') {
        this.app_importVisible = true
      } else if (command === 'firmware') {
        this.firmware_importVisible = true
      }
    },
    handleDeleteSn() {
      this.$commonConfirm().showDeleteDialog(this.$t('common.common_confirm.delete_title'), this.$t('common.common_confirm.delete_content_devices'), this.$t('common.delete'), this.confirmDeleteDevice)
    },
    confirmDeleteDevice() {
      delBatchLegalDevices({
        batchId: this.batchId,
        devSnList: this.selectedData
      }).then((res) => {
        if (res !== undefined && res !== '') {
          if (res.batchName === undefined) {
            this.$message.error(
              this.$t('batch.tip_delDevice_error1', { devSn: res.sn })
            )
          } else {
            this.$message.error(
              this.$t('batch.tip_delDevice_error3', {
                devSn: res.sn,
                name: res.name
              })
            )
          }
        } else {
          this.$message.success(this.$t('page.delete_success'))
          this.freshTerminalCount()
        }
      })
      this.$commonConfirm().close()
    },
    handleCommandExport() {
      this.loading = false
      this.$confirm(
        this.$t('batch.download_devices_tip'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('page.confirm'),
          cancelButtonText: this.$t('page.cancel'),
          type: 'warning'
        })
        .then(() => {
          let startTime, endTime
          if (this.activeDate) {
            this.activeDate.forEach((val, index) => {
              if (index === 0) {
                startTime = val / 1000
              } else if (index === 1) {
                endTime = val / 1000 + 24 * 60 * 60
              }
            })
          }
          this.downLoad(
            import.meta.env.VITE_APP_BASE_API +
            '/online/management/admin/batch/device/file/export',
            'Group-device-export-' + this.getNowTime() + '.xlsx',
            {
              batchId: this.batchId,
              isValid: this.isVaild,
              snOrTid: this.snOrTid,
              status: this.status,
              operatorName: this.operatorName,
              mrchNameOrMid: this.mrchNameOrMid,
              activeStartTime: startTime,
              activeEndTime: endTime,
              recursive: 1
            })
        })
    },
    handleCommandDelete(command) {
      this.loading = false
      this.command = command
      if (command === 'inputBoxSn') {
        this.inputBox_deleteVisibleSn = true
      } else if (command === 'inputBoxTid') {
        this.inputBox_deleteVisibleTid = true
      } else if (command === 'file') {
        this.file_deleteVisible = true
      }
    },
    // 下载模板
    downLoad(url, fileName, params) {
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: {
          'WEB-TOKEN': getToken(),
          LANG:
            localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
        },
        params: params
      }).then(({ data }) => {
        if (data) {
          var url = window.URL.createObjectURL(data)
          var a = document.createElement('a')
          a.href = url
          a.download = fileName
          a.click()
        } else {
          this.$message.error('Download error')
        }
      }).catch(this.$confirmError)
    },
    format(time, format) {
      var t = new Date(time)
      var tf = function(i) {
        return (i < 10 ? '0' : '') + i
      }
      return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
        switch (a) {
          case 'yyyy':
            return tf(t.getFullYear())
          case 'MM':
            return tf(t.getMonth() + 1)
          case 'mm':
            return tf(t.getMinutes())
          case 'dd':
            return tf(t.getDate())
          case 'HH':
            return tf(t.getHours())
          case 'ss':
            return tf(t.getSeconds())
        }
      })
    },
    getNowTime() {
      // var timezone = 8; //目标时区时间，东八区
      var timezone = 0 - new Date().getTimezoneOffset() / 60
      console.log(timezone)
      var offset_GMT = new Date().getTimezoneOffset() // 本地时间和格林威治的时间差，单位为分钟
      var nowDate = new Date().getTime() // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
      var targetDate = new Date(
        nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000
      )
      return this.format(targetDate, 'YYYYMMDD-HHmmss')
    },
    formatDate(row, column, cellValue, index) {
      return parseTime(cellValue, '{y}-{m}-{d}')
    }
  }
}
</script>

<style lang='scss' scoped>
.group-terminal {
  .icon-button {
  }
}

.device-online {
  color: #059669
}

.device-offline {
  color: #D97706
}
</style>
